﻿using FlickrNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WindowsLive.Writer.Api;

namespace FlickrHarmony {
	public partial class InsertSetForm : Form {
		const string _homeUrl = "http://www.flickr.com/";

		public InsertSetForm() {
			this.InitializeComponent();
			if (string.IsNullOrEmpty(Plugin.Profile.ImagePattern)) {
				Plugin.Profile.ImagePattern = "<p>x</p>" + Environment.NewLine + "<div class='photo'><img alt='{title}' src='{url}'/></div>";
			}
			txtPattern.Text = Plugin.Profile.ImagePattern;
			progressBar.Show();
			this.DoWork(this.LoadSetsWorker);
		}

		internal List<Photo> Photos { get; set; }
		internal string Pattern { get; set; }
		internal ImageSize ImageSize { get; set; }

		string Status {
			set {
				this.RunInMainThread(() => {
					lblStatus.Text = value;
					if (value.Length < 1) {
						// default the curser back
						Cursor.Current = Cursors.Default;
						lblStatus.Text = "Idle";
					} else {
						// we are actually doing something, let's pause the cursor
						Cursor.Current = Cursors.WaitCursor;
					}
				});
			}
		}

		#region Events

		private void lstSets_SelectedIndexChanged(object sender, EventArgs e) {
			this.btnInsert.Hide();
			this.progressBar.Show();
			this.DoWork(this.LoadPhotosWorker);
		}

		private void btnCancel_Click(object sender, EventArgs e) {
			base.DialogResult = DialogResult.Cancel;
		}

		private void btnInsert_Click(object sender, EventArgs e) {
			this.Pattern = txtPattern.Text;
			base.DialogResult = DialogResult.OK;

			if (rdbSize500.Checked) {
				this.ImageSize = FlickrHarmony.ImageSize.Medium500;
			} else if (rdbSize640.Checked) {
				this.ImageSize = FlickrHarmony.ImageSize.Medium640;
			} else if (rdbSize1024.Checked) {
				this.ImageSize = FlickrHarmony.ImageSize.Large1024;
			} else {
				this.ImageSize = FlickrHarmony.ImageSize.Original;
			}
		}

		private void InsertSetForm_FormClosed(object sender, FormClosedEventArgs e) {
			try { LoadSetsWorker.CancelAsync(); } catch { }
		}

		private void flickrLogo_Click(object sender, EventArgs e) { this.GotoUrl(_homeUrl); }

		private void txtPattern_TextChanged(object sender, EventArgs e) {
			Plugin.Profile.ImagePattern = txtPattern.Text;
		}

		#endregion

		#region Background Threads

		void LoadSetsWorker_DoWork(object sender, DoWorkEventArgs e) {
			this.Status = "Loading Your Flickr Sets";
			var sets = Plugin.Flickr.PhotosetsGetList(Plugin.Profile.UserID);
			this.RunInMainThread(() => {
				lstSets.Enabled = true;
				lstSets.DataSource = sets;
				lstSets.ValueMember = "PhotosetId";
				lstSets.DisplayMember = "Title";
				lstSets.SelectedIndexChanged += new System.EventHandler(this.lstSets_SelectedIndexChanged);
				progressBar.Hide();
			});
			this.Status = string.Format("Loaded {0} Sets", sets.Count);
		}

		void LoadPhotosWorker_DoWork(object sender, DoWorkEventArgs e) {
			string setID = this.ValueFromMainThread(() => (string)lstSets.SelectedValue);
			var photos = Plugin.Flickr.PhotosetsGetPhotos(setID, 1, 200);
			this.Photos = new List<Photo>();
			foreach (var p in photos) { this.Photos.Add(p); }

			this.RunInMainThread(() => {
				this.btnInsert.Enabled = true;
				this.btnInsert.Text = string.Format("Insert {0} Photo{1}",
					this.Photos.Count,
					((this.Photos.Count == 1) ? "" : "s")
				);
				this.btnInsert.Show();
				this.progressBar.Hide();
			});
			this.Status = "Ready";
		}

		#endregion

		/// <summary>
		/// Launch default handler (browser) for a URL
		/// </summary>
		void GotoUrl(string url) {
			try {
				System.Diagnostics.Process.Start(url);
			} catch (Exception ex) {
				PluginDiagnostics.DisplayUnexpectedException(ex);
			}
		}

		void ClearStatus() { this.Status = string.Empty; }		
	}
}
